package com.example.roam.game.emeimountain.view;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import com.example.roam.game.emeimountain.control.GameFirstControlEms;

public class GameFirstUiEms extends SurfaceView implements SurfaceHolder.Callback{

    private SurfaceHolder surfaceHolder;
    private GameFirstControlEms gameFirstControlEms;

    public GameFirstUiEms(Context context) {
        super(context);
        initGame();
    }

    public GameFirstUiEms(Context context, AttributeSet attrs) {
        super(context, attrs);
        initGame();
    }

    public GameFirstUiEms(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initGame();
    }

    private void initGame(){
        surfaceHolder = this.getHolder();
        surfaceHolder.addCallback(this);
        gameFirstControlEms = new GameFirstControlEms(getContext());
    }

    @Override
    public void surfaceCreated(@NonNull SurfaceHolder holder) {
        Runner runner = new Runner();
        runner.start();
    }

    @Override
    public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder holder) {

    }

    class Runner extends Thread{
        @Override
        public void run() {
            while (gameFirstControlEms.isVisible) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                draw();
            }
        }
    }

    public void draw(){
        Canvas canvas = surfaceHolder.lockCanvas();
        gameFirstControlEms.draw(canvas);
        surfaceHolder.unlockCanvasAndPost(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gameFirstControlEms.onTouch(event);
        return true;
    }

    public GameFirstControlEms getGameFirstControlEms() {
        return gameFirstControlEms;
    }
}
